package com.example.mobilesafe.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.mobilesafe.R;
import com.example.mobilesafe.constant.ConstantValue;
import com.example.mobilesafe.dao.AddressDao;
import com.example.mobilesafe.utils.SharedPreferencesUtil;

public class AddressService extends Service {

    private TelephonyManager mSystemService;

    private MyPhoneStateListener mPhoneStateListener;

    // Layout对象
    private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();

    // 自定义的Toast布局
    private View mViewToast;

    // 获取窗体对象
    private WindowManager mWindowsManager;

    // 归属地信息
    private String mAddress;

    // 归属地信息显示控件
    private TextView tv_toast;

    // 存储资源图片id的数组
    private int[] mDrawableIds;

    // ViewToast的X坐标
    private int startX;

    // ViewToast的Y坐标
    private int startY;

    // 窗体的宽度
    private int mScreenWidth;

    // 窗体的高度
    private int mScreenHeight;

    // 监听打出电话的广播接收器
    private InnerOutCallReceiver mInnerOutCallReceiver;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            tv_toast.setText(mAddress);
        }
    };


    @Override
    public void onCreate() {
        super.onCreate();
        // 第一次开启服务时，就需要管理Toast的显示
        // 同时，还需要监听电话的状态（服务开启时监听，关闭时电话状态就不需要监听了）

        // 1.电话管理者对象
        mSystemService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        mPhoneStateListener = new MyPhoneStateListener();

        // 2.监听电话状态
        mSystemService.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        // 5.获取窗体对象
        mWindowsManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        mScreenHeight = mWindowsManager.getDefaultDisplay().getHeight();
        mScreenWidth = mWindowsManager.getDefaultDisplay().getWidth();

        // 监听播出电话的广播过滤条件
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
        // 创建广播接受者
        mInnerOutCallReceiver = new InnerOutCallReceiver();
        registerReceiver(mInnerOutCallReceiver,intentFilter);
    }

    // 创建一个内部广播接收器
    public class InnerOutCallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 接收到此广播后，需要显示自定义的Toast，显示播出归属地号码
            String phone = getResultData();
            showToast(phone);
        }
    }

    // 3.实现一个继承了PhoneStateListener的内部类
    class MyPhoneStateListener extends PhoneStateListener{
        // 4.手动重写，电话状态发生改变时会触发的方法
        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            super.onCallStateChanged(state, phoneNumber);
            switch (state){
                case TelephonyManager.CALL_STATE_IDLE:
                    // 空闲状态，没有任何活动，挂断电话时需要移除Toast
                    if (mWindowsManager != null && mViewToast != null){
                        mWindowsManager.removeView(mViewToast);
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    // 摘机状态，至少有个电话活动，该活动是拨打或者通话
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    // 响铃状态
                    showToast(phoneNumber);
                    break;
            }
        }
    }

    /**
     * 打印Toast
     */
    public void showToast(String phoneNumber) {
        // 自定义Toast
        final WindowManager.LayoutParams params = mParams;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        params.format = PixelFormat.TRANSLUCENT;
        params.type = WindowManager.LayoutParams.TYPE_PHONE; // 在响铃的时候显示Toast，和电话类型一致
        params.gravity = Gravity.LEFT + Gravity.TOP; // 指定位置到左上角
        // 自定义了Toast的布局，需要将xml转换成view，将Toast挂到windowManager窗体上
        mViewToast = View.inflate(this, R.layout.toast_view, null);
        tv_toast = mViewToast.findViewById(R.id.tv_toast);

        mViewToast.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int moveX = (int) event.getRawX();
                        int moveY = (int) event.getRawY();

                        int disX = moveX - startX;
                        int disY = moveY - startY;

                        // 赋值给自定义控件
                        params.x = params.x + disX;
                        params.y = params.y + disY;

                        // 容错处理
                        if (params.x < 0){
                            params.x = 0;
                        }
                        if (params.y < 0){
                            params.y = 0;
                        }
                        if (params.x > mScreenWidth - mViewToast.getWidth()){
                            params.x = mScreenWidth - mViewToast.getWidth();
                        }
                        if (params.y > mScreenHeight - mViewToast.getHeight() - 22){
                            params.y = mScreenHeight - mViewToast.getHeight() - 22;

                        }

                        // 根据手势移动，在窗体上去进行自定义控件位置的更新
                        mWindowsManager.updateViewLayout(mViewToast,params);

                        // 重置一次起始坐标
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        SharedPreferencesUtil.putInt(getApplicationContext(),ConstantValue.LOCATION_X,params.x);
                        SharedPreferencesUtil.putInt(getApplicationContext(),ConstantValue.LOCATION_Y,params.y);
                        break;
                }
                // 在当前的情况下返回false表示不响应事件，返回true才表示响应事件
                // 既要响应点击事件，又要响应拖拽过程，则此返回值结果需要修改为false
                return true;
            }
        });

        // 读取sp中存储Toast左上角坐标值（x,y）
        int localX = SharedPreferencesUtil.getInt(getApplicationContext(), ConstantValue.LOCATION_X, 0);
        int localY = SharedPreferencesUtil.getInt(getApplicationContext(), ConstantValue.LOCATION_Y, 0);

        // 将读取的坐标值赋给params（这里的坐标默认代表左上角）
        params.x = localX;
        params.y = localY;


        // 从sp中后去色值文字的索引，匹配图片，用作展示
        mDrawableIds = new int[]{R.drawable.function_greenbutton_normal,
                R.drawable.function_greenbutton_normal,
                R.drawable.function_greenbutton_normal,
                R.drawable.function_greenbutton_normal,
                R.drawable.function_greenbutton_normal};
        int toastStyle = SharedPreferencesUtil.getInt(getApplicationContext(), ConstantValue.TOAST_STYLE, 0);
        tv_toast.setBackgroundResource(mDrawableIds[toastStyle]);

        mWindowsManager.addView(mViewToast,params); // 在窗体上挂载View

        // 获取了来电号码以后，需要做来电号码查询
        query(phoneNumber);
    }

    private void query(final String phoneNumber){
        new Thread(){
            @Override
            public void run() {
                mAddress = AddressDao.getAddress(phoneNumber);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 取消对电话状态的监听
        if (mSystemService != null && mPhoneStateListener != null){
            mSystemService.listen(mPhoneStateListener,PhoneStateListener.LISTEN_NONE);
        }
        if (mInnerOutCallReceiver != null){
            // 对广播接受者的注销
            unregisterReceiver(mInnerOutCallReceiver);
        }
    }
}